const { request } = require("express");

// 加载 db 模块
const db = require('../db')

// 这里存放个人中心的路由
const express = require('express');
const e = require("express");
const { md5 } = require("utility");
const router = express.Router();

// 将路由对象挂载到接口上
// ===================== 获取用户信息接口 =======================
router.get('/userinfo', async(req,res) => {
    let r = await db('select * from user where id=?',req.user.id);
    if(r && r.length > 0) {
        res.send({status: 0, message: '获取用户信息成功', data: r[0]});
    }else {
        res.send({status: 1, message: '获取用户信息失败'});
    }
})

// ===================== 更新用户信息接口 =======================
router.post('/userinfo', async(req,res) => {
    let sql = 'update user set ? where id=?';
    let r = await db(sql,[req.body,req.body.id]);
    if(r && r.affectedRows > 0) {
        res.send({status: 0, message: '更新用户信息成功'});
    }else {
        res.send({status: 1, message: '更新用户信息失败'});
    }
})

// ===================== 重置密码接口 =======================
router.post('/updatepwd', async(req,res) => {
    // console.log(req.body)
    // 对新密码加密   
    let oldPwd = md5(req.body.oldPwd);
    let newPwd = md5(req.body.newPwd);
    // 判断原密码是否正确
    let r1 = await db('select * from user where password=? and id=?',[oldPwd,req.user.id]);
    if(r1 && r1.length > 0) {
        let r2 = await db('update user set password=? where id=?',[newPwd,req.user.id]);
        if(r2 && r2.affectedRows > 0) {
            res.send({status: 0, message: '更新密码成功'});
        }else {
            res.send({status: 1, message: '更新密码失败'});
        }
    }else {
        res.send({status: 1, message: '原密码错误'});
    }
})

// ===================== 更改头像接口 =======================
router.post('/update/avatar', async(req,res) => {
    // 接收 base64 格式的字符串
    let r = await db('update user set user_pic=? where id=?',[req.body.avatar,req.user.id]);
    if(r && r.affectedRows > 0) {
        res.send({status: 0, message: '更新头像成功'})
    }else {
        res.send({status: 1, message: '更新头像失败'})
    }
})

module.exports = router;